package org.vergil.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.vergil.dto.Jwt;
import org.vergil.dto.Playload;
import org.vergil.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * Created by vergil on 4/29/17.
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String jwtContext = httpServletRequest.getHeader("jwt");
        if (null == jwtContext && !"".equals(jwtContext)){
            return false;
        }
        Jwt jwt = JwtUtils.decodeJwt(jwtContext);
        Playload playload = jwt.getPlayload();
        LocalDateTime expTime = LocalDateTime.parse(playload.getExp());
        Long flag = Duration.between(LocalDateTime.now(),expTime).toMillis();
        if (flag < 0L){
            return false;
        }
        if (redisTemplate.hasKey(jwt.getSignature())) {
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
